<template>
  <ui-container :hasSearch="false">
    <template #extra>
      <u-button @click="handleOnClickToRefresh"> 刷新 </u-button>
      <u-button
        type="primary"
        color="#28a745"
        @click="handleOnClickToSaveRulePermission"
      >
        保存授权
      </u-button>
      <u-button type="primary" @click="handleOnClickToBack">返回 </u-button>
    </template>
    <template #container>
      <a-transfer
        :data-source="dataSource"
        :titles="['源数据资源', '已授权资源']"
        :target-keys="ruleIdList"
        :show-select-all="false"
        :render="(item) => item.title"
        :operations="['加入授权', '取消授权']"
        @change="handleOnChangeToUpdateTransfer"
      >
        <template #children="{ direction, selectedKeys, onItemSelect }">
          <a-tree
            v-if="direction === 'left' && treeData.length > 0"
            blockNode
            checkable
            checkStrictly
            defaultExpandAll
            :checkedKeys="[...selectedKeys, ...ruleIdList]"
            :treeData="treeData"
            :replace-fields="replaceFields"
            @check="
              (_, props) => {
                handleOnCheckToUpdatePermissionList(
                  _,
                  props,
                  [...selectedKeys, ...ruleIdList],
                  onItemSelect
                );
              }
            "
            @select="
              (_, props) => {
                handleOnCheckToUpdatePermissionList(
                  _,
                  props,
                  [...selectedKeys, ...ruleIdList],
                  onItemSelect
                );
              }
            "
          />
        </template>
      </a-transfer>
    </template>
  </ui-container>
</template>

<script>
import UIContainer from "basicLayoutComponent/UIContainer";
import UICLI from "components/ui-cli";
import { Tree, Transfer, Switch } from "ant-design-vue";

import {
  getPermissionIdListByRuleId,
  saveRulePermission,
} from "@/access/api/role/index";

import { getPermissionForTreeList } from "@/access/api/permission/index";

import { showMess, confirm } from "utils/Util";

export default {
  name: "RoleAuthorize",
  components: {
    UiContainer: UIContainer,
    UButton: UICLI.UButton,
    ATransfer: Transfer,
    ATree: Tree,
    ASwitch: Switch,
  },
  data() {
    return {
      query: {
        id: -1,
      },
      treeData: [],
      ruleIdList: [],
      replaceFields: {
        children: "children",
        title: "permissionName",
        key: "id",
      },
      dataSource: [],
      saved: false,
    };
  },
  methods: {
    init() {
      this.initParams();
    },
    initParams() {
      this.query.id = this.$route.params.id;
    },
    getPermissionForTreeByRuleGroupId() {
      getPermissionForTreeList({
        ruleId: this.query.id,
      }).then((res) => {
        if (res) {
          this.treeData = res;

          this.getTransferDataSource(res);
        }
      });
    },
    getTransferDataSource(list = []) {
      if (list) {
        list.forEach((item) => {
          this.dataSource.push({
            key: item.id,
            title: item.permissionName,
          });
          this.getTransferDataSource(item.children);
        });
      }
    },
    getPermissionIdListByRuleId() {
      getPermissionIdListByRuleId({
        ruleId: this.query.id,
      }).then((res) => {
        if (res) {
          this.ruleIdList = res;
        }
      });
    },
    handleOnChangeToUpdateTransfer(targetKeys, direction) {
      this.ruleIdList = targetKeys;
    },
    handleOnCheckToUpdatePermissionList(_, e, checkedKeys, onItemSelect) {
      this.totalChecked = _;
      const { eventKey } = e.node;
      onItemSelect(eventKey, !this.isChecked(checkedKeys, eventKey));
    },
    isChecked(selectedKeys, eventKey) {
      return selectedKeys.indexOf(eventKey) !== -1;
    },

    handleOnClickToSaveRulePermission() {
      saveRulePermission({
        ruleId: this.query.id,
        permissionIds: this.ruleIdList,
      }).then((res) => {
        if (res) {
          this.saved = true;
          showMess("授权成功");
          this.handleOnClickToBack();
        }
      });
    },
    handleOnClickToBack() {
      /**
       * 比较合理的情况应该判断：
       *  1. 如果没有再次选择授权资源，那么不提示
       *  2. 如果选择了授权资源并且添加到了右边，那么退出的时候需要进行提示
       * 
       * 这里只做简单判断
       */
      if (this.saved) {
        this.$router.push("/list/rule");
      } else {
        confirm(() => {
          this.$router.push("/list/rule");
        }, "授权资源还没有保存，确认返回么?");
      }
    },
    handleOnClickToRefresh() {
      this.getPermissionForTreeByRuleGroupId();
      this.getPermissionIdListByRuleId();
    }
  },
  created() {
    this.init();
    this.getPermissionForTreeByRuleGroupId();
    this.getPermissionIdListByRuleId();
  },
};
</script>

<style lang="less" scoped>
</style>